<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Menu extends BaseModel
{
    use HasFactory;
    protected $table = 'sys_menu';
    public $timestamps = false;
    protected $guarded = [];
    public function children()
    {
        return $this->hasMany(get_class($this), 'parent_id');
    }

    public function allChildren()
    {
        return $this->children()->with('allChildren');
    }
    public function creator()
    {
        return $this->belongsTo(\App\Models\User::class);
    }
    public function scopeRelatedJoin($query)
    {
        $id = $this->escapeSql(get("id"));
        if ($id) {
            $query->addSelect("{$this->getTable()}.*");
            $query->addSelect(DB::raw("(SELECT COUNT(*) FROM sys_role_menu a LEFT JOIN sys_role b on a.role_id=b.id WHERE a.menu_id ={$this->getTable()}.id and a.role_id={$id}) as permissions"));
        }
    }
}
